package logic

import (
	"context"
	"fmt"
	"user/model/mysql"
	"user/model/redis"
	"user/pkg"

	"user/userrpc/internal/svc"
	"user/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *userrpc.UpdateRequest) (*userrpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line
	var users mysql.User
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&users)

	get := redis.Client.Get("CaptchaUpdate" + in.Account)
	if get.Val() != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证码错误,请重新输入")
	}

	sms := redis.Client.Get("SendSmsUpdate" + in.Phone)
	if sms.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("手机短信验证码错误,请重新输入")
	}

	if users.Password != pkg.Md5Pwd(in.OldPassword) {
		return nil, fmt.Errorf("输入的旧密码有误,请重新输入")
	}
	if in.Password != in.NewPassword {
		return nil, fmt.Errorf("两次输入的密码不一致,请重新输入")
	}
	if pkg.Md5Pwd(in.Password) == users.Password {
		return nil, fmt.Errorf("新密码不能和旧密码一致,请重新输入")
	}

	var user mysql.User
	user.Password = pkg.Md5Pwd(in.Password)
	err := mysql.DB.Debug().Updates(&user).Error
	if err != nil {
		return nil, fmt.Errorf("修改失败")
	}
	redis.Client.Del("CaptchaLogin" + in.Account)
	redis.Client.Del("SendSmsLogin" + in.Phone)
	return &userrpc.UpdateResponse{Id: int64(user.Id)}, nil
}
